<?php
  
  class Torrent {
    
    public $details;
    
    public function Torrent($details) {
      $this->details = $details;
    }
    
    public function getHash() {
      return $this->details["hash"];
    }
    
    public function getName() {
      if (strlen($this->details["name"])>25)
        return substr($this->details["name"], 0, 25) . "...";
      return $this->details["name"];
    }

    public function getPercentage() {
      return floor(($this->details["completed_chunks"] / $this->details["size_in_chunks"]) * 100);
    }
    
    public function getRatio() {
      return $this->details["ratio"];
    }
    
    public function getSize() {
      return  $this->getCorrectUnits($this->details["size_in_chunks"] * $this->details["chunk_size"]);
    }
    
    public function getDownloaded() {
      return $this->getCorrectUnits($this->details["completed_chunks"] * $this->details["chunk_size"]);
    }
    
    public function getUploaded() {
      return $this->getCorrectUnits($this->details["completed_chunks"] * $this->details["chunk_size"] * $this->details["ratio"]);
    }
    
    public function getDownloadRate() {
      return $this->details["down_rate"] . "Kbps";
    }
    
    public function getUploadRate() {
      return $this->details["up_rate"] . "Kbps";
    }
    
    public function getSeeds() {
      return $this->details["seeds"];
    }
    
    public function getPeers() {
      return $this->details["peers"];
    }
    
    public function getState() {
      $state = 1;
      if ($this->details["state"] == 0) {
        $state = 0; // Stopped
      }
      
      else {
        if ($this->getPercentage() != 100)
          $state = 1; // Active
        else
          $state = 2; // Seeding
      }
      
      if ($this->details["open"] != 1)
        $state = -1; // Closed
      
      if ($this->details["hashchecking"] == 1)
        $state = 3; // Hash checking
        
      return $state;
    }
    
    private function getCorrectUnits($size) {
      $size_units = "bytes";
      if($size >= 1024) {
        $size /= 1024;
        $size_units = "Kb";
      }
      
      if($size >= 1024) {
        $size /= 1024;
        $size_units = "Mb";
      }
      
      if($size >= 1024) {
        $size /= 1024;
        $size_units = "Gb";
      }
      
      return round($size, 2) .  $size_units;
    }
  
  }
  
?>